<!-- templates/root.html -->
{% extends "layout.html" %}
{% from "_macros.html" import render_modal %}

{% block content %}
<div class="container-fluid">
    <ul class="nav nav-tabs" id="mainTabs" role="tablist">
        <li class="nav-item"><a class="nav-link active" id="videos-tab" data-toggle="tab" href="#videos" role="tab">Videos</a></li>
        <li class="nav-item"><a class="nav-link" id="datasets-tab" data-toggle="tab" href="#datasets" role="tab">Datasets</a></li>
        <li class="nav-item"><a class="nav-link" id="models-tab" data-toggle="tab" href="#models" role="tab">Models</a></li>
        <li class="nav-item"><a class="nav-link" id="settings-tab" data-toggle="tab" href="#settings" role="tab">Settings</a></li>
    </ul>

    <div class="tab-content mt-3">
        <!-- Videos Tab -->
        <div class="tab-pane fade show active" id="videos" role="tabpanel">
            <h2>Videos</h2>
            <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#uploadVideoModal">Upload Video</button>
            <input type="file" id="frame-import-input" webkitdirectory directory multiple style="display: none;" />
            <table class="table table-hover">
                <thead><tr><th>Description</th><th>Filename</th><th>Status</th><th>Frames</th><th>Labeled</th><th>Actions</th></tr></thead>
                <tbody id="video-list"></tbody>
            </table>
        </div>

        <!-- Datasets Tab -->
        <div class="tab-pane fade" id="datasets" role="tabpanel">
            <h2>Datasets</h2>
            <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#createDatasetModal">Create Dataset</button>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Included Videos</th>
                        <th>Classes</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="dataset-list"></tbody>
            </table>
        </div>

        <!-- Models Tab -->
        <div class="tab-pane fade" id="models" role="tabpanel">
             <h2>Models</h2>
            <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#importModelModal">Import TFLite Model</button>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Created Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="model-list"></tbody>
            </table>
        </div>

        <!-- Settings Tab -->
        <div class="tab-pane fade" id="settings" role="tabpanel">
            <h2>Application Settings</h2>
            <p>Changes to the SAM model will take effect on the next annotation or tracking task.</p>
            <form id="settings-form" class="mt-3 col-md-8 col-lg-6">
                <div class="card">
                    <div class="card-header">
                        AI Model Settings
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="setting-sam-model">Annotation Assistance Model (SAM)</label>
                            <select id="setting-sam-model" class="form-control">
                                <option value="sam2.1_t.pt" data-name="SAM 2.1 Tiny">SAM 2.1 Tiny</option>
                                <option value="sam2.1_s.pt" data-name="SAM 2.1 Small">SAM 2.1 Small</option>
                                <option value="sam2.1_b.pt" data-name="SAM 2.1 Base">SAM 2.1 Base</option>
                                <option value="sam2.1_l.pt" data-name="SAM 2.1 Large">SAM 2.1 Large</option>
                            </select>
                            <small class="form-text text-muted">Larger models are more accurate but significantly slower and use more memory.</small>
                        </div>
                    </div>
                </div>

                <div class="card mt-4">
                    <div class="card-header">
                        General Settings
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="setting-jpeg-quality">Frame Extraction JPEG Quality</label>
                            <input type="number" id="setting-jpeg-quality" class="form-control" min="10" max="100" step="5">
                             <small class="form-text text-muted">Affects disk space usage and image quality for new video uploads (10-100).</small>
                        </div>
                        <div class="form-group">
                            <label for="setting-opencv-tracker">Default OpenCV Tracker</label>
                            <select id="setting-opencv-tracker" class="form-control">
                                {% for tracker in tracker_fns %}
                                <option value="{{ tracker }}">{{ tracker }}</option>
                                {% endfor %}
                            </select>
                            <small class="form-text text-muted">This is for the legacy object tracking feature.</small>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary mt-4">Save Settings</button>
            </form>
        </div>
    </div>
</div>

<!-- Modals -->
{% call render_modal('uploadVideoModal', 'Upload a New Video') %}
    <form id="upload-video-form">
        <div class="form-group">
            <label for="video-description">Description</label>
            <input type="text" class="form-control" id="video-description" name="description" placeholder="A short, unique description" required maxlength="{{ limit_data.MAX_DESCRIPTION_LENGTH }}">
        </div>
        <div class="form-group">
            <label for="video-file">Video File</label>
            <input type="file" class="form-control-file" id="video-file" name="video_file" accept="video/mp4" required>
            <small class="form-text text-muted">Max size: {{ limit_data.MAX_VIDEO_SIZE_MB }}MB. Only .mp4 is supported.</small>
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
{% endcall %}

{% call render_modal('createDatasetModal', 'Create a New Dataset') %}
    <form id="create-dataset-form">
        <div class="form-group">
            <label for="dataset-description">Dataset Description</label>
            <input type="text" class="form-control" id="dataset-description" placeholder="Unique description for the dataset" required maxlength="{{ limit_data.MAX_DESCRIPTION_LENGTH }}">
        </div>
        <div class="form-group">
            <label for="dataset-videos">Select Videos (must be READY and have labeled frames)</label>
            <select multiple class="form-control" id="dataset-videos" required size="8">
            </select>
            <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple videos.</small>
        </div>
        <div class="form-group">
            <label for="eval-percent">Validation Set Percentage (%)</label>
            <input type="number" class="form-control" id="eval-percent" value="20" min="5" max="50" step="1">
        </div>
        <div class="form-group">
            <label for="test-percent">Test Set Percentage (%)</label>
            <input type="number" class="form-control" id="test-percent" value="10" min="0" max="50" step="1">
        </div>
        <button type="submit" class="btn btn-primary">Create</button>
    </form>
{% endcall %}

{% call render_modal('importModelModal', 'Import a TFLite Model') %}
    <form id="import-model-form">
        <div class="form-group">
            <label for="model-description">Model Description</label>
            <input type="text" class="form-control" id="model-description" name="description" placeholder="A short, unique description" required maxlength="{{ limit_data.MAX_DESCRIPTION_LENGTH }}">
        </div>
        <div class="form-group">
            <label for="model-file">TFLite File</label>
            <input type="file" class="form-control-file" id="model-file" name="model_file" accept=".tflite" required>
            <small class="form-text text-muted">Only .tflite models are supported.</small>
        </div>
        <button type="submit" class="btn btn-primary">Import</button>
    </form>
{% endcall %}

<div class="modal fade" id="manageTasksModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="manageTasksModalTitle">Manage Annotation Tasks for: </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h6>Existing Tasks</h6>
                <table class="table table-sm">
                    <thead><tr><th>Assigned To</th><th>Frame Range</th><th>Description</th><th>Actions</th></tr></thead>
                    <tbody id="task-list-in-modal"></tbody>
                </table>
                <hr>
                <h6>Create New Task</h6>
                <form id="create-task-form">
                    <input type="hidden" id="task-video-uuid">
                    <div class="form-row">
                        <div class="form-group col-md-4">
                            <label for="task-assigned-to">Assign To (User)</label>
                            <input type="text" class="form-control" id="task-assigned-to" placeholder="e.g., Alice" required>
                        </div>
                        <div class="form-group col-md-3">
                            <label for="task-start-frame">Start Frame</label>
                            <input type="number" class="form-control" id="task-start-frame" min="0" required>
                        </div>
                        <div class="form-group col-md-3">
                            <label for="task-end-frame">End Frame</label>
                            <input type="number" class="form-control" id="task-end-frame" min="0" required>
                        </div>
                    </div>
                     <div class="form-group">
                        <label for="task-description">Task Description (Optional)</label>
                        <input type="text" class="form-control" id="task-description" placeholder="e.g., Label all cars in daytime scenes">
                    </div>
                    <button type="submit" class="btn btn-primary">Create Task</button>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // --- Helper Functions ---
    function getStatusBadge(status) {
        let badgeClass = 'secondary';
        if (status === 'READY') badgeClass = 'success';
        if (status === 'PROCESSING' || status === 'EXTRACTING' || status === 'PENDING') badgeClass = 'info';
        if (status === 'FAILED') badgeClass = 'danger';
        return `<span class="badge badge-${badgeClass}">${status}</span>`;
    }

    function showSuccess(message) {
        alert(message);
    }

    function showError(message) {
        alert('Error: ' + message);
    }

    // --- Refresh Functions ---
    function refreshVideos() {
        $.get('/listVideos', function(data) {
            const videoList = $('#video-list');
            videoList.empty();
            data.all_videos.forEach(video => {
                const actionBtnDisabled = video.status !== 'READY' ? 'disabled' : '';
                const row = `
                    <tr>
                        <td>${video.description}</td>
                        <td>${video.video_filename || ''}</td>
                        <td>${getStatusBadge(video.status)} <small class="text-muted">${video.status_message || ''}</small></td>
                        <td>${video.extracted_frame_count} / ${video.frame_count || '?'}</td>
                        <td>${video.labeled_frame_count}</td>
                        <td>
                            <button class="btn btn-sm btn-success btn-manage-tasks"
                                    data-uuid="${video.video_uuid}"
                                    data-description="${video.description}"
                                    data-frameCount="${video.frame_count}"
                                    ${actionBtnDisabled}>
                                Manage Tasks
                            </button>
                            <button class="btn btn-sm btn-info btn-import-frames ${actionBtnDisabled}" data-uuid="${video.video_uuid}">Import Frames</button>
                            <button class="btn btn-sm btn-danger btn-delete-video" data-uuid="${video.video_uuid}">Delete</button>
                        </td>
                    </tr>`;
                videoList.append(row);
            });

            const datasetVideoSelect = $('#dataset-videos');
            datasetVideoSelect.empty();
            data.ready_videos_for_dataset.forEach(video => {
                 datasetVideoSelect.append(`<option value="${video.video_uuid}">${video.description} (${video.labeled_frame_count} labeled frames)</option>`);
            });
        });
    }

    function refreshDatasets() {
        $.get('/listDatasets', function(data) {
            const datasetList = $('#dataset-list');
            datasetList.empty();
            data.datasets.forEach(dataset => {
                let actions = `<button class="btn btn-sm btn-danger btn-delete-dataset" data-uuid="${dataset.dataset_uuid}">Delete</button>`;
                if (dataset.status === 'READY') {
                    actions = `<a href="/downloadDataset/${dataset.dataset_uuid}" class="btn btn-sm btn-success">Download</a> ` + actions;
                }
                const videos = JSON.parse(dataset.video_uuids || '[]').length;
                const classes = JSON.parse(dataset.sorted_label_list || '[]').join(', ');

                const row = `
                    <tr>
                        <td>${dataset.description}</td>
                        <td>${getStatusBadge(dataset.status)} <small class="text-muted">${dataset.status_message || ''}</small></td>
                        <td>${videos} video(s)</td>
                        <td>${classes}</td>
                        <td>${actions}</td>
                    </tr>`;
                datasetList.append(row);
            });
        });
    }

    function refreshModels() {
        $.get('/listModels', function(data) {
            const modelList = $('#model-list');
            modelList.empty();
            data.models.forEach(model => {
                const createdDate = new Date(model.create_time_ms).toLocaleString();
                const row = `
                    <tr>
                        <td>${model.description}</td>
                        <td>${createdDate}</td>
                        <td>
                            <button class="btn btn-sm btn-danger btn-delete-model" data-uuid="${model.model_uuid}">Delete</button>
                        </td>
                    </tr>`;
                modelList.append(row);
            });
        });
    }

    function loadSettings() {
        $.get('/api/settings', function(data) {
            if (data.success) {
                const settings = data.settings;
                $('#setting-sam-model').val(settings.sam_model_checkpoint);
                $('#setting-jpeg-quality').val(settings.frame_extraction_jpeg_quality);
                $('#setting-opencv-tracker').val(settings.default_opencv_tracker);
            }
        });
    }

    // --- Form Submission Handlers ---
    $('#upload-video-form').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        $.ajax({
            url: '/uploadVideo', type: 'POST', data: formData, processData: false, contentType: false,
            success: function(response) {
                if (response.success) {
                    showSuccess('Video uploaded successfully! Frame extraction has started.');
                    $('#uploadVideoModal').modal('hide');
                    refreshVideos();
                } else { showError(response.message); }
            },
            error: function(xhr) { showError(xhr.responseJSON ? xhr.responseJSON.message : 'An unknown error occurred.'); }
        });
    });

    $('#create-dataset-form').on('submit', function(e) {
        e.preventDefault();
        const datasetData = {
            description: $('#dataset-description').val(),
            video_uuids: $('#dataset-videos').val(),
            eval_percent: $('#eval-percent').val(),
            test_percent: $('#test-percent').val()
        };
        $.ajax({
            url: '/createDataset', type: 'POST', contentType: 'application/json', data: JSON.stringify(datasetData),
            success: function(response) {
                if (response.success) {
                    showSuccess('Dataset creation started!');
                    $('#createDatasetModal').modal('hide');
                    refreshDatasets();
                } else { showError(response.message); }
            },
            error: function(xhr) { showError(xhr.responseJSON ? xhr.responseJSON.message : 'An unknown error occurred.'); }
        });
    });

    $('#import-model-form').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        $.ajax({
            url: '/importModel', type: 'POST', data: formData, processData: false, contentType: false,
            success: function(response) {
                if (response.success) {
                    showSuccess('Model imported successfully!');
                    $('#importModelModal').modal('hide');
                    refreshModels();
                } else { showError(response.message); }
            },
            error: function(xhr) { showError(xhr.responseJSON ? xhr.responseJSON.message : 'An unknown error occurred.'); }
        });
    });

    $('#settings-form').on('submit', function(e) {
        e.preventDefault();
        const selectedOption = $('#setting-sam-model').find('option:selected');
        const settingsData = {
            sam_model_checkpoint: selectedOption.val(),
            sam_model_name: selectedOption.data('name'),
            frame_extraction_jpeg_quality: parseInt($('#setting-jpeg-quality').val()),
            default_opencv_tracker: $('#setting-opencv-tracker').val()
        };
        $.ajax({
            url: '/api/settings', type: 'POST', contentType: 'application/json', data: JSON.stringify(settingsData),
            success: function(response) {
                if (response.success) {
                    if (response.restart_required) {
                        alert("Settings saved! The SAM model was changed. The new model will be loaded automatically for the next task.");
                    } else {
                        alert("Settings saved successfully!");
                    }
                } else { showError(response.message); }
            },
            error: function(xhr) { showError(xhr.responseJSON ? xhr.responseJSON.message : 'An unknown error occurred.'); }
        });
    });

    // --- Task Management ---
    $(document).on("click", ".btn-manage-tasks", function() {
        const videoUuid = $(this).data("uuid");
        const videoDesc = $(this).data("description");
        const frameCount = $(this).data("framecount");
        $('#manageTasksModalTitle').text('Manage Annotation Tasks for: ' + videoDesc);
        $('#task-video-uuid').val(videoUuid);
        $('#task-start-frame').attr('max', frameCount - 1);
        $('#task-end-frame').attr('max', frameCount - 1);
        refreshTasksInModal(videoUuid);
        $('#manageTasksModal').modal('show');
    });

    function refreshTasksInModal(videoUuid) {
        const taskListBody = $('#task-list-in-modal');
        taskListBody.empty().append('<tr><td colspan="4">Loading...</td></tr>');
        $.get(`/listTasks?video_uuid=${videoUuid}`, function(data) {
            taskListBody.empty();
            if (data.success && data.tasks.length > 0) {
                data.tasks.forEach(task => {
                    const row = `
                        <tr>
                            <td>${task.assigned_to}</td>
                            <td>${task.start_frame} - ${task.end_frame}</td>
                            <td>${task.description || ''}</td>
                            <td>
                                <a href="/labelVideo?task_uuid=${task.task_uuid}" class="btn btn-sm btn-primary" target="_blank">Start Labeling</a>
                                <button class="btn btn-sm btn-danger btn-delete-task" data-task-uuid="${task.task_uuid}" data-video-uuid="${videoUuid}">Delete</button>
                            </td>
                        </tr>`;
                    taskListBody.append(row);
                });
            } else {
                taskListBody.append('<tr><td colspan="4">No tasks created for this video yet.</td></tr>');
            }
        });
    }

    $('#create-task-form').on('submit', function(e) {
        e.preventDefault();
        const videoUuid = $('#task-video-uuid').val();
        const taskData = { video_uuid: videoUuid, assigned_to: $('#task-assigned-to').val(), description: $('#task-description').val(), start_frame: $('#task-start-frame').val(), end_frame: $('#task-end-frame').val(), };
        $.ajax({
            url: '/createTask', type: 'POST', contentType: 'application/json', data: JSON.stringify(taskData),
            success: function(response) {
                if (response.success) {
                    showSuccess('Task created successfully!');
                    $('#create-task-form')[0].reset();
                    refreshTasksInModal(videoUuid);
                } else { showError(response.message); }
            },
            error: function() { showError('An error occurred while creating the task.'); }
        });
    });

    // --- Deletion Handlers ---
    $(document).on("click", ".btn-delete-video", function() {
        if (confirm('Are you sure you want to delete this video and all its data?')) { $.ajax({url: '/deleteVideo', type: 'POST', contentType: 'application/json', data: JSON.stringify({ video_uuid: $(this).data('uuid') }), success: refreshVideos }); }
    });
    $(document).on("click", ".btn-delete-task", function() {
        const videoUuid = $(this).data('video-uuid');
        if (confirm('Are you sure you want to delete this task?')) { $.ajax({url: '/deleteTask', type: 'POST', contentType: 'application/json', data: JSON.stringify({ task_uuid: $(this).data('task-uuid') }), success: function() { refreshTasksInModal(videoUuid); } }); }
    });
    $(document).on("click", ".btn-delete-dataset", function() {
        if (confirm('Are you sure you want to delete this dataset?')) { $.ajax({url: '/deleteDataset', type: 'POST', contentType: 'application/json', data: JSON.stringify({ dataset_uuid: $(this).data('uuid') }), success: refreshDatasets }); }
    });
    $(document).on("click", ".btn-delete-model", function() {
        if (confirm('Are you sure you want to delete this model?')) { $.ajax({url: '/deleteModel', type: 'POST', contentType: 'application/json', data: JSON.stringify({ model_uuid: $(this).data('uuid') }), success: refreshModels }); }
    });

    // --- Initial Load & Refresh Interval ---
    function runAllRefreshes() {
        refreshVideos();
        refreshDatasets();
        refreshModels();
    }

    loadSettings();
    runAllRefreshes();
    setInterval(runAllRefreshes, 5000);
});
</script>
{% endblock %}